#include "head.h"
int exitpipe[2];
void sigFunc(int signum){
    printf("process pool is going to exit!\n");
    write(exitpipe[1],"1",1);
}
int main(int argc, char *argv[])
{
    // ./server 0.0.0.0 1234 3
    ARGS_CHECK(argc,4);
    int workerNum = atoi(argv[3]);
    workerdata_t * workerdataArr = (workerdata_t *)calloc(workerNum,sizeof(workerdata_t));
    makeWorker(workerNum,workerdataArr);
    pipe(exitpipe);
    signal(SIGUSR1,sigFunc);
    int sockfd;
    tcpInit(&sockfd,argv[1],argv[2]);
    int epfd = epoll_create(1);
    // 把sockfd加入监听
    epollAdd(epfd,sockfd);
    // 把exitpipe的读端加入监听
    epollAdd(epfd,exitpipe[0]);
    // 每个子进程的socket管道加入监听
    for(int i = 0; i < workerNum; ++i){
        epollAdd(epfd,workerdataArr[i].socketfd);
    }
    int readyMax = workerNum+1;
    while(1){
        struct epoll_event *readySet = (struct epoll_event *)calloc(readyMax,sizeof(struct epoll_event));
        int readyNum = epoll_wait(epfd,readySet,readyMax,-1);
        for(int i = 0; i < readyNum; ++i){
            if(readySet[i].data.fd == sockfd){
                // 客户端接入
                printf("master, client connect\n");
                int netfd = accept(sockfd,NULL,NULL);
                // 发给一个空闲的子进程
                for(int j = 0; j < workerNum; ++j){
                    if(workerdataArr[j].status == FREE){
                        printf("No %d worker got his job, pid = %d\n", j, workerdataArr[j].pid);
                        sendfd(workerdataArr[j].socketfd, netfd, 0);
                        workerdataArr[j].status = BUSY;
                        break;
                    }
                }
                //
                close(netfd);
            }
            else if(readySet[i].data.fd == exitpipe[0]){
                // 子进程终止的逻辑
                for(int j = 0; j < workerNum; ++j){
                    //kill(workerdataArr[j].pid,SIGKILL);
                    sendfd(workerdataArr[j].socketfd, 0, 1);
                    printf("kill 1 worker!\n");
                }
                for(int j = 0; j < workerNum; ++j){
                    wait(NULL);
                }
                printf("master is going to exit!\n");
                exit(0);
            }
            else{//子进程完成任务
                printf("master, 1 child finishes his job!\n");
                for(int j = 0; j < workerNum; ++j){
                    if(workerdataArr[j].socketfd == readySet[i].data.fd){
                        pid_t pid;
                        read(workerdataArr[j].socketfd,&pid,sizeof(pid));
                        printf("No %d worker, pid = %d\n",j, pid);
                        workerdataArr[j].status = FREE;
                        break;
                    }
                }

            }
        }
    }
    return 0;
}

